package handlers

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"

	"iot/sql_models"
)

// DisconnectHandler 处理 MQTT "disconnect" 事件
func DisconnectHandler(c *gin.Context) {
	// 获取请求中的 JSON 数据
	var jsonData map[string]interface{}
	if err := c.ShouldBindJSON(&jsonData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 启动 Goroutine 处理断开连接事件
	go handleDisconnect(jsonData)

	// 返回响应，防止阻塞
	c.JSON(http.StatusOK, gin.H{"status": "disconnect event received"})
}

// handleDisconnect 是异步处理断开连接事件的函数
func handleDisconnect(data map[string]interface{}) {
	// fmt.Printf("\n\n\n\n\n\n")
	// fmt.Printf("Handling disconnect event: %v\n", data)
	clientID := data["clientid"].(string)
	fmt.Printf("ClientID: %v\n", clientID)

	timestamp := parseTimestamp(data, "timestamp")
	fmt.Println("Parsed Time:", timestamp)

	var oldLog sql_models.ConnectionLog
	if err := sql_models.DB.Where("client_id = ?", clientID).First(&oldLog).Error; err != nil {
		fmt.Println("设备未记录")
		return
	}

	sql_models.UpdateDisconnectionLog(&oldLog, timestamp)
	if err := sql_models.DB.Save(&oldLog).Error; err != nil {
		fmt.Println("更新断连日志失败:", err)
		return
	}

	fmt.Println("更新设备断连时间成功")
}
